import UIKit
import Photos
import SnapKit

class YCPhotoPreviewViewController: UIViewController {
    
    // MARK: - Properties
    
    private var fetchResult: PHFetchResult<PHAsset>
    private let initialIndex: Int
    private let itemSpacing: CGFloat = 30
    
    private let bottomToolBarH: CGFloat = 56
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 30
        layout.minimumInteritemSpacing = 0
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.isPagingEnabled = true
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(YCPhotoPreviewCell.self, forCellWithReuseIdentifier: "YCPhotoPreviewCell")
        return collectionView
    }()
    
    private let closeButton: UIButton = {
        let button = UIButton(type: .system)
        let config = UIImage.SymbolConfiguration(pointSize: 16, weight: .medium)
        let image = UIImage(systemName: "xmark", withConfiguration: config)
        button.setImage(image, for: .normal)
        button.tintColor = .white
        return button
    }()
    
    private lazy var bottomToolBar: UIVisualEffectView = {
        let blurEffect = UIBlurEffect(style: .dark)
        let visualEffectView = UIVisualEffectView(effect: blurEffect)
        visualEffectView.layer.cornerRadius = bottomToolBarH / 2
        visualEffectView.layer.masksToBounds = true
        return visualEffectView
    }()
    
    private let hideButton: UIButton = {
        let button = UIButton(type: .system)
        let config = UIImage.SymbolConfiguration(pointSize: 15, weight: .medium)
        let image = UIImage(systemName: "eye.slash", withConfiguration: config)
        button.setImage(image, for: .normal)
        button.tintColor = .white

        return button
    }()
    
    private let favoriteButton: UIButton = {
        let button = UIButton(type: .system)
        let config = UIImage.SymbolConfiguration(pointSize: 15, weight: .medium)
        let image = UIImage(systemName: "heart", withConfiguration: config)
        button.setImage(image, for: .normal)
        button.tintColor = .white
        
        return button
    }()
    
    private let deleteButton: UIButton = {
        let button = UIButton(type: .system)
        let config = UIImage.SymbolConfiguration(pointSize: 15, weight: .medium)
        let image = UIImage(systemName: "trash", withConfiguration: config)
        button.setImage(image, for: .normal)
        button.tintColor = .white

        return button
    }()
    
    // 添加新属性
    private var isControlsVisible = true
    private let controlsAnimationDuration: TimeInterval = 0.3
    
    // 修改 bottomToolBar 的约束属性
    private var bottomToolBarBottomConstraint: Constraint?
    
    // 添加单击手势识别器
    private lazy var tapGesture: UITapGestureRecognizer = {
        let gesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        return gesture
    }()
    
    // 添加保存缩略图位置信息的属性
    private var sourceImageFrame: CGRect = .zero
    
    // 添加一个字典属性来存储所有图片的位置信息
    private var thumbnailFrames: [Int: CGRect] = [:]
    private var currentAssetIndex: Int = 0
    
    // MARK: - Initialization
    
    init(fetchResult: PHFetchResult<PHAsset>, initialIndex: Int, thumbnailFrames: [Int: CGRect]) {
        self.fetchResult = fetchResult
        self.initialIndex = initialIndex
        self.currentAssetIndex = initialIndex
        self.thumbnailFrames = thumbnailFrames
        self.sourceImageFrame = thumbnailFrames[initialIndex] ?? .zero
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .overFullScreen
        modalTransitionStyle = .coverVertical
    }
    
    init(fetchResult: PHFetchResult<PHAsset>, initialIndex: Int) {
        self.fetchResult = fetchResult
        self.initialIndex = initialIndex
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .overFullScreen
        modalTransitionStyle = .coverVertical
    }
    
    deinit {
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        // 注册照片库变化观察者
        PHPhotoLibrary.shared().register(self)
        
        // 滚动到初始图片并更新按钮状态
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            let indexPath = IndexPath(item: self.initialIndex, section: 0)
            self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
            self.updateButtonStates(at: indexPath)
        }
    }
    
    override var prefersStatusBarHidden: Bool {
        return true
    }
    
    // MARK: - Setup
    
    private func setupUI() {
        view.backgroundColor = .black
        view.addSubview(collectionView)
        // 往左偏移itemSpacing的一半
        collectionView.frame = CGRect(x: -itemSpacing / 2, y: 0, width: view.yc.width + itemSpacing, height: view.yc.height)
        
        // 添加单击手势
        view.addGestureRecognizer(tapGesture)
        
        // 修改 bottomToolBar 约束，保存 bottom 约束以便动画
        view.addSubview(bottomToolBar)
        bottomToolBar.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            bottomToolBarBottomConstraint = make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-20).constraint
            make.height.equalTo(bottomToolBarH)
            make.width.equalTo(180)
        }
        
        // 创建按钮容器视图
        let buttonContainer = UIView()
        bottomToolBar.contentView.addSubview(buttonContainer)
        buttonContainer.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.top.equalToSuperview().offset((bottomToolBarH - 44) / 2)
            make.height.equalTo(44)
        }
        
        // 设置按钮大小和布局
        [hideButton, favoriteButton, deleteButton].forEach { button in
            buttonContainer.addSubview(button)
            button.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: 44, height: 44))
            }
        }
        
        // 水平布局按钮
        hideButton.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        favoriteButton.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        deleteButton.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        // 添加按钮触摸效果
        [hideButton, favoriteButton, deleteButton].forEach { button in
            button.addTarget(self, action: #selector(buttonTouchDown(_:)), for: .touchDown)
            button.addTarget(self, action: #selector(buttonTouchUp(_:)), for: [.touchUpInside, .touchUpOutside])
        }
        
        // 添加按钮点击事件
        hideButton.addTarget(self, action: #selector(hideButtonTapped), for: .touchUpInside)
        favoriteButton.addTarget(self, action: #selector(favoriteButtonTapped), for: .touchUpInside)
        deleteButton.addTarget(self, action: #selector(deleteButtonTapped), for: .touchUpInside)
    }
    
    // MARK: - Actions
    
    @objc private func closeButtonTapped() {
        dismiss(animated: true)
    }
    
    @objc private func hideButtonTapped() {
        guard let currentIndexPath = getCurrentIndexPath() else { return }
        let asset = fetchResult.object(at: currentIndexPath.item)
        
        PHPhotoLibrary.requestAuthorization { [weak self] status in
            guard let self = self else { return }
            
            if status == .authorized {
                PHPhotoLibrary.shared().performChanges({
                    let request = PHAssetChangeRequest(for: asset)
                    request.isHidden = !asset.isHidden
                }) { success, error in
                    DispatchQueue.main.async {
                        if success {
                            self.updateHideButtonState(for: asset)
                            self.showToast(message: asset.isHidden ? "已显示" : "已隐藏")
                            // 添加触觉反馈
                            let generator = UIImpactFeedbackGenerator(style: .medium)
                            generator.impactOccurred()
                        } else {
                            
                        }
                    }
                }
            } else {
                DispatchQueue.main.async {
                    self.showPhotoLibraryPermissionAlert()
                }
            }
        }
    }
    
    @objc private func favoriteButtonTapped() {
        guard let currentIndexPath = getCurrentIndexPath() else { return }
        let asset = fetchResult.object(at: currentIndexPath.item)
        let willBeFavorite = !asset.isFavorite  // 保存即将变更的状态
        
        PHPhotoLibrary.requestAuthorization { [weak self] status in
            guard let self = self else { return }
            
            if status == .authorized {
                PHPhotoLibrary.shared().performChanges({
                    let request = PHAssetChangeRequest(for: asset)
                    request.isFavorite = willBeFavorite
                }) { success, error in
                    DispatchQueue.main.async {
                        if success {
                            // 直接使用 willBeFavorite 更新按钮状态，而不是使用 asset.isFavorite
                            let config = UIImage.SymbolConfiguration(pointSize: 15, weight: .medium)
                            let imageName = willBeFavorite ? "heart.fill" : "heart"
                            let image = UIImage(systemName: imageName, withConfiguration: config)
                            
                            UIView.transition(with: self.favoriteButton, duration: 0.2, options: .transitionCrossDissolve) {
                                self.favoriteButton.setImage(image, for: .normal)
                                self.favoriteButton.tintColor = willBeFavorite ? .systemPink : .white
                            }
                            
                            self.showToast(message: willBeFavorite ? "已收藏" : "已取消收藏")
                            // 添加触觉反馈
                            let generator = UIImpactFeedbackGenerator(style: .medium)
                            generator.impactOccurred()
                        }
                    }
                }
            } else {
                DispatchQueue.main.async {
                    self.showPhotoLibraryPermissionAlert()
                }
            }
        }
    }
    
    @objc private func deleteButtonTapped() {
        guard let currentIndexPath = getCurrentIndexPath() else { return }
        let asset = fetchResult.object(at: currentIndexPath.item)
        
        // 按钮点击触觉反馈
        let buttonFeedback = UIImpactFeedbackGenerator(style: .medium)
        buttonFeedback.impactOccurred()
        
        // 准备删除结果的反馈生成器
        let resultFeedback = UINotificationFeedbackGenerator()
        resultFeedback.prepare()
        
        // 保存当前索引，用于后续处理
        let currentIndex = currentAssetIndex
        
        // 计算下一个要显示的索引
        let nextIndex: Int
        if currentIndex >= fetchResult.count - 1 {
            // 如果是最后一张，显示前一张
            nextIndex = max(0, currentIndex - 1)
        } else {
            // 否则显示下一张
            nextIndex = currentIndex + 1
        }
        
        // 如果只有一张照片，直接删除
        if fetchResult.count == 1 {
            // 系统会自动显示确认对话框
            PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.deleteAssets([asset] as NSFastEnumeration)
            }) { success, error in
                if success {
                    DispatchQueue.main.async {
                        resultFeedback.notificationOccurred(.success)
                        self.showToast(message: "已删除")
                        self.dismiss(animated: true)
                    }
                }
            }
            return
        }
        
        // 使用系统的删除确认对话框
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.deleteAssets([asset] as NSFastEnumeration)
        }) { [weak self] success, error in
            guard let self = self else { return }
            
            DispatchQueue.main.async {
                
                if success {
                    resultFeedback.notificationOccurred(.success)
                    // 用户确认删除后，执行过渡动画
                    let indexPath = IndexPath(item: nextIndex, section: 0)
                    // 更新当前索引
                    self.currentAssetIndex = nextIndex
                    
                    // 更新按钮状态
                    self.updateButtonStates(at: indexPath)
                
                } else {
                    resultFeedback.notificationOccurred(.error)
                }
            }
        }
    }
    
    @objc private func buttonTouchDown(_ button: UIButton) {
        UIView.animate(withDuration: 0.1) {
            button.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
            button.alpha = 0.8
        }
    }
    
    @objc private func buttonTouchUp(_ button: UIButton) {
        UIView.animate(withDuration: 0.1) {
            button.transform = .identity
            button.alpha = 1.0
        }
    }
    
    private func updateHideButtonState(for asset: PHAsset) {
        let config = UIImage.SymbolConfiguration(pointSize: 15, weight: .medium)
        let imageName = asset.isHidden ? "eye" : "eye.slash"
        let image = UIImage(systemName: imageName, withConfiguration: config)
        
        UIView.transition(with: hideButton, duration: 0.2, options: .transitionCrossDissolve) {
            self.hideButton.setImage(image, for: .normal)
        }
    }
    
    @objc private func handleTap() {
        toggleControlsVisibility()
    }
    
    private func toggleControlsVisibility() {
        isControlsVisible.toggle()
        
        // 计算底部工具栏应该移动的距离
        let safeAreaBottom = view.safeAreaInsets.bottom
        // 显示时距离底部安全区域20点，隐藏时刚好移出屏幕
        let bottomOffset = isControlsVisible ? -20 : (bottomToolBarH + safeAreaBottom + 20)
        let alpha: CGFloat = isControlsVisible ? 1.0 : 0.0
        
        // 更新约束
        bottomToolBarBottomConstraint?.update(offset: bottomOffset)
        
        // 执行动画
        UIView.animate(withDuration: controlsAnimationDuration,
                      delay: 0,
                      options: [.curveEaseInOut],
                      animations: {
            // 更新约束
            self.view.layoutIfNeeded()
            
            // 更新透明度
            self.closeButton.alpha = alpha
            self.bottomToolBar.alpha = alpha
            // 同步更新底部工具栏上的按钮透明度
            self.hideButton.alpha = alpha
            self.favoriteButton.alpha = alpha
            self.deleteButton.alpha = alpha
        })
    }
    
    // 在视图即将出现时确保控件可见
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        isControlsVisible = true
        closeButton.alpha = 1.0
        bottomToolBar.alpha = 1.0
        bottomToolBarBottomConstraint?.update(offset: -20)
        view.layoutIfNeeded()
    }
    
    // MARK: - Helper Methods
    
    private func deleteAsset(_ asset: PHAsset) {
        // 准备删除结果的反馈生成器
        let resultFeedback = UINotificationFeedbackGenerator()
        resultFeedback.prepare() // 提前准备，减少延迟
        
        // 保存当前索引，用于后续处理
        let currentIndex = currentAssetIndex
        
        // 计算下一个要显示的索引
        let nextIndex: Int
        if currentIndex >= fetchResult.count - 1 {
            // 如果是最后一张，显示前一张
            nextIndex = max(0, currentIndex - 1)
        } else {
            // 否则显示下一张
            nextIndex = currentIndex + 1
        }
        
        // 如果只有一张照片，直接删除
        if fetchResult.count == 1 {
            performDeletion(asset: asset, resultFeedback: resultFeedback)
            return
        }
        
        // 使用动画滚动到下一张图片
        let indexPath = IndexPath(item: nextIndex, section: 0)
        
        // 添加过渡动画
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut) {
            // 先淡出当前视图
            self.collectionView.alpha = 0
        } completion: { _ in
            // 滚动到新的位置
            self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
            
            // 更新当前索引
            self.currentAssetIndex = nextIndex
            
            // 更新按钮状态
            self.updateButtonStates(at: indexPath)
            
            // 淡入显示新视图
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut) {
                self.collectionView.alpha = 1
            } completion: { _ in
                // 动画完成后执行删除操作
                self.performDeletion(asset: asset, resultFeedback: resultFeedback)
            }
        }
    }
    
    // 将删除操作抽取为单独的方法
    private func performDeletion(asset: PHAsset, resultFeedback: UINotificationFeedbackGenerator) {
        PHPhotoLibrary.requestAuthorization { [weak self] status in
            guard let self = self else { return }
            
            if status == .authorized {
                PHPhotoLibrary.shared().performChanges({
                    PHAssetChangeRequest.deleteAssets([asset] as NSFastEnumeration)
                }) { success, error in
                    DispatchQueue.main.async {
                        if success {
                            // 删除成功时触发震动
                            resultFeedback.notificationOccurred(.success)
                            
                            self.showToast(message: "已删除")
                            
                            if self.fetchResult.count == 0 {
                                self.dismiss(animated: true)
                            }
                        } else {
                            // 删除失败时触发错误震动
                            resultFeedback.notificationOccurred(.error)
                        }
                    }
                }
            } else {
                DispatchQueue.main.async {
                    // 权限不足时触发警告震动
                    resultFeedback.notificationOccurred(.warning)
                    
                    self.showPhotoLibraryPermissionAlert()
                }
            }
        }
    }
    
    private func getCurrentIndexPath() -> IndexPath? {
        let visibleRect = CGRect(origin: collectionView.contentOffset, size: collectionView.bounds.size)
        let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
        return collectionView.indexPathForItem(at: visiblePoint)
    }
    
    private func showToast(message: String) {
        let toast = UILabel()
        toast.text = message
        toast.textColor = .white
        toast.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        toast.textAlignment = .center
        toast.font = .systemFont(ofSize: 14)
        toast.layer.cornerRadius = 15
        toast.clipsToBounds = true
        toast.alpha = 0
        
        view.addSubview(toast)
        toast.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(120)
            make.height.equalTo(30)
        }
        
        UIView.animate(withDuration: 0.3, animations: {
            toast.alpha = 1
        }) { _ in
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                UIView.animate(withDuration: 0.3, animations: {
                    toast.alpha = 0
                }) { _ in
                    toast.removeFromSuperview()
                }
            }
        }
    }
    
    // 添加权限提示方法
    private func showPhotoLibraryPermissionAlert() {
        let alert = UIAlertController(
            title: "需要访问照片权限",
            message: "请在设置中允许访问照片，以便进行相关操作。",
            preferredStyle: .alert
        )
        
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        alert.addAction(UIAlertAction(title: "去设置", style: .default) { _ in
            if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(settingsURL)
            }
        })
        
        present(alert, animated: true)
    }
    
    // MARK: - UICollectionViewDelegate
    
    // 确保滚动时不影响点击手势
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        tapGesture.isEnabled = !scrollView.isDragging && !scrollView.isDecelerating
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        tapGesture.isEnabled = true
        if let currentIndexPath = getCurrentIndexPath() {
            currentAssetIndex = currentIndexPath.item
            updateButtonStates(at: currentIndexPath)
        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            tapGesture.isEnabled = true
        }
    }

    // 更新所有按钮状态
    private func updateButtonStates(at indexPath: IndexPath) {
        let asset = fetchResult.object(at: indexPath.item)
        // 更新收藏按钮状态
        let config = UIImage.SymbolConfiguration(pointSize: 15, weight: .medium)
        let imageName = asset.isFavorite ? "heart.fill" : "heart"
        let image = UIImage(systemName: imageName, withConfiguration: config)
        
        UIView.transition(with: favoriteButton, duration: 0.2, options: .transitionCrossDissolve) {
            self.favoriteButton.setImage(image, for: .normal)
            self.favoriteButton.tintColor = asset.isFavorite ? .systemPink : .white
        }
        
        updateHideButtonState(for: asset)
    }
    
    // 实现新的动画方法
    private func animateBackToCenter(_ cell: YCPhotoPreviewCell) {
        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0) {
            cell.containerView.transform = .identity
            cell.containerView.center = cell.initialCenter
            self.view.backgroundColor = .black
            self.bottomToolBar.alpha = 1
            self.bottomToolBarBottomConstraint?.update(offset: -20)
            self.view.layoutIfNeeded()
        }
    }
    
    // 修改关闭动画方法
    private func animateToDismiss(_ cell: YCPhotoPreviewCell) {
        // 获取当前图片在视图中的位置
        let currentFrame = cell.containerView.convert(cell.containerView.bounds, to: nil)
        
        // 创建一个动画视图，保持当前图片的外观
        let animationView = UIImageView(frame: currentFrame)
        
        // 获取当前索引
        if let indexPath = getCurrentIndexPath() {
            currentAssetIndex = indexPath.item
        }
        
        // 检查是否有普通图片
        if cell.imageView.image != nil {
            animationView.image = cell.imageView.image
            animationView.contentMode = .scaleAspectFit
        } 
        // 检查是否有 LivePhoto
        else if cell.livePhotoView.livePhoto != nil {
            // 对于 LivePhoto，使用 PHImageManager 获取预览图
            let asset = fetchResult.object(at: currentAssetIndex)
            
            let options = PHImageRequestOptions()
            options.deliveryMode = .highQualityFormat
            options.isNetworkAccessAllowed = true
            options.resizeMode = .exact
            
            PHImageManager.default().requestImage(
                for: asset,
                targetSize: view.bounds.size,
                contentMode: .aspectFit,
                options: options
            ) { image, _ in
                if let image = image {
                    animationView.image = image
                    animationView.contentMode = .scaleAspectFit
                }
            }
        }
        
        view.addSubview(animationView)
        
        // 隐藏原始视图
        cell.containerView.isHidden = true
        
        // 检查当前索引的缩略图是否在可见区域内
        if let thumbnailFrame = thumbnailFrames[currentAssetIndex], !thumbnailFrame.isEmpty {
            // 可见区域内的图片：执行缩放动画到对应的缩略图位置
            UIView.animate(withDuration: 0.35, delay: 0, options: .curveEaseInOut) {
                // 背景变透明
                self.view.backgroundColor = .black.withAlphaComponent(0)
                self.bottomToolBar.alpha = 0
                
                // 将图片动画到目标位置
                animationView.frame = thumbnailFrame
                
                // 动画结束时切换到与缩略图相同的显示模式
                animationView.contentMode = .scaleAspectFill
                animationView.clipsToBounds = true
                
                // 添加圆角效果
                animationView.layer.cornerRadius = 5
            } completion: { _ in
                animationView.removeFromSuperview()
                self.dismiss(animated: false)
            }
        } else {
            // 不在可见区域内的图片：执行中心缩小淡出动画
            
            // 计算屏幕中心位置
            let screenCenter = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
            
            // 设置初始缩放和透明度
            animationView.contentMode = .scaleAspectFit
            
            // 执行动画
            UIView.animate(withDuration: 0.35, delay: 0, options: .curveEaseInOut) {
                // 背景淡出
                self.view.backgroundColor = .black.withAlphaComponent(0)
                self.bottomToolBar.alpha = 0
                
                // 图片缩小并淡出
                let smallSize = CGSize(width: currentFrame.width * 0.3, height: currentFrame.height * 0.3)
                animationView.frame = CGRect(
                    x: screenCenter.x - smallSize.width/2,
                    y: screenCenter.y - smallSize.height/2,
                    width: smallSize.width,
                    height: smallSize.height
                )
                animationView.alpha = 0
            } completion: { _ in
                animationView.removeFromSuperview()
                self.dismiss(animated: false)
            }
        }
    }
}

// MARK: - UICollectionViewDataSource

extension YCPhotoPreviewViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return fetchResult.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YCPhotoPreviewCell", for: indexPath) as! YCPhotoPreviewCell
        let asset = fetchResult.object(at: indexPath.item)
        cell.delegate = self
        cell.configure(with: asset)
        return cell
    }
}

// MARK: - UICollectionViewDelegateFlowLayout

extension YCPhotoPreviewViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.yc.width, height: view.yc.height)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: itemSpacing / 2, bottom: 0, right: itemSpacing / 2)
    }
}

// 修改 PHPhotoLibraryChangeObserver 的实现
extension YCPhotoPreviewViewController: PHPhotoLibraryChangeObserver {
    func photoLibraryDidChange(_ changeInstance: PHChange) {
        // 仅处理实际资源变更（如增加、删除、移动）
        guard let changes = changeInstance.changeDetails(for: self.fetchResult),
              // 验证是否有真正的内容变化，而不仅是元数据更新
              (changes.removedIndexes?.count ?? 0 > 0 || 
               changes.insertedIndexes?.count ?? 0 > 0 || 
               changes.changedIndexes?.count ?? 0 > 0 || 
               changes.hasMoves) else {
            return // 如果只是图片加载导致的元数据变化，直接忽略
        }
        
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            
            // 更新数据源
            self.fetchResult = changes.fetchResultAfterChanges
            
            // 判断是否需要完全重新加载
            let needsReloadData = changes.hasMoves || 
                                 (self.fetchResult.count != changes.fetchResultBeforeChanges.count)
            
            if needsReloadData {
                // 重新加载全部数据
                self.collectionView.reloadData()
            } else if let changedIndexes = changes.changedIndexes, changedIndexes.count > 0 {
                // 仅更新已更改的单元格
                let changedIndexPaths = changedIndexes.map { IndexPath(item: $0, section: 0) }
                self.collectionView.reloadItems(at: changedIndexPaths)
            }
        }
    }
}

// MARK: - UIGestureRecognizerDelegate

extension YCPhotoPreviewViewController: UIGestureRecognizerDelegate {
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if gestureRecognizer == tapGesture {
            return true
        }
        return false
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, 
                          shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return false
    }
}

// 实现 YCPhotoPreviewCellDelegate
extension YCPhotoPreviewViewController: YCPhotoPreviewCellDelegate {
    func cellDidBeginDragging(_ cell: YCPhotoPreviewCell) {
        // 开始拖动时，隐藏底部工具栏
        UIView.animate(withDuration: 0.2) {
            self.bottomToolBar.alpha = 0
        }
    }
    
    func cell(_ cell: YCPhotoPreviewCell, didDragWithProgress progress: CGFloat) {
        // 只有当progress为正值（向下拖动）时才改变背景和底部工具栏
        if progress > 0 {
            // 计算背景透明度 - 只在向下拖动时变化
            let alphaValue = max(0.1, 1.0 - progress)
            view.backgroundColor = .black.withAlphaComponent(alphaValue)
            
            // 底部工具栏只改变透明度，不改变位置
            // 比背景更快消失
            bottomToolBar.alpha = max(0, 1 - progress * 2)
            
            // 移除之前对底部工具栏位置的修改代码
            // 不再需要更新底部工具栏的位置约束
        } else {
            // 当向上拖动回到原位或更高时，保持原始状态
            view.backgroundColor = .black.withAlphaComponent(1.0)
            bottomToolBar.alpha = isControlsVisible ? 1.0 : 0.0
        }
    }
    
    func cellDidEndDragging(_ cell: YCPhotoPreviewCell, shouldDismiss: Bool) {
        if shouldDismiss {
            // 使用新的关闭动画
            animateToDismiss(cell)
        } else {
            // 使用弹性动画回到原位
            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.2, options: .curveEaseOut) {
                cell.containerView.transform = .identity
                cell.containerView.center = cell.initialCenter
                self.view.backgroundColor = .black
                
                // 只恢复透明度，不改变位置
                self.bottomToolBar.alpha = self.isControlsVisible ? 1 : 0
                self.view.layoutIfNeeded()
            }
        }
    }
    
    func cellDidCancelDragging(_ cell: YCPhotoPreviewCell) {
        // 使用弹性动画回到原位
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.2, options: .curveEaseOut) {
            cell.containerView.transform = .identity
            cell.containerView.center = cell.initialCenter
            self.view.backgroundColor = .black
            
            // 只恢复透明度，不改变位置
            self.bottomToolBar.alpha = self.isControlsVisible ? 1 : 0
            self.view.layoutIfNeeded()
        }
    }
}
